/**
 * Supabase配置文件
 * 提供数据库连接、认证和存储服务
 */

import { createClient, SupabaseClient } from '@supabase/supabase-js';

// Supabase配置
const SUPABASE_URL = process.env.VUE_APP_SUPABASE_URL || 'https://your-project.supabase.co';
const SUPABASE_ANON_KEY = process.env.VUE_APP_SUPABASE_ANON_KEY || 'your-anon-key';

// 配置验证
function validateSupabaseConfig(): void {
  if (SUPABASE_URL === 'https://your-project.supabase.co') {
    console.warn('⚠️ Supabase URL 未配置，请在.env文件中设置 VUE_APP_SUPABASE_URL');
  }
  if (SUPABASE_ANON_KEY === 'your-anon-key') {
    console.warn('⚠️ Supabase ANON KEY 未配置，请在.env文件中设置 VUE_APP_SUPABASE_ANON_KEY');
  }
  
  console.log('🔧 Supabase配置信息:');
  console.log('URL:', SUPABASE_URL);
  console.log('ANON_KEY:', SUPABASE_ANON_KEY ? `${SUPABASE_ANON_KEY.substring(0, 10)}...` : '未设置');
}

// 验证配置
validateSupabaseConfig();

// 创建Supabase客户端
export const supabase: SupabaseClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  auth: {
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: true
  },
  realtime: {
    params: {
      eventsPerSecond: 10
    }
  }
});

// 数据库表名常量
export const TABLES = {
  USERS: 'users',
  BABY_PROFILES: 'baby_profiles',
  CHAT_SESSIONS: 'chat_sessions',
  MESSAGES: 'messages',
  CONTENTS: 'contents',
  GROWTH_RECORDS: 'growth_records',
  INTERACTIONS: 'interactions',
  COMMENTS: 'comments',
  LIKES: 'likes'
} as const;

// 存储桶名称
export const STORAGE_BUCKETS = {
  AVATARS: 'avatars',
  BABY_PHOTOS: 'baby-photos',
  CONTENT_MEDIA: 'content-media',
  CHAT_MEDIA: 'chat-media'
} as const;

// 用户接口定义
export interface User {
  id: string;
  phone: string;
  nickname: string;
  avatar_url?: string;
  city?: string;
  membership_type: 'basic' | 'premium' | 'expert';
  platform: 'mp-weixin' | 'mp-toutiao' | 'mp-xiaohongshu' | 'app-plus' | 'h5' | 'unknown';
  openid?: string;
  unionid?: string;
  device_info: Record<string, any>;
  created_at: string;
  updated_at: string;
}

// 宝宝档案接口定义
export interface BabyProfile {
  id: string;
  user_id: string;
  name: string;
  birth_date: string;
  gender: 'male' | 'female';
  weight?: number;
  height?: number;
  preferences: Record<string, any>;
  created_at: string;
}

// 聊天会话接口定义
export interface ChatSession {
  id: string;
  user_id: string;
  baby_id?: string;
  title?: string;
  last_message?: string;
  context: Record<string, any>;
  created_at: string;
  updated_at: string;
}

// 消息接口定义
export interface Message {
  id: string;
  session_id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  media_type?: string;
  media_url?: string;
  confidence?: number;
  created_at: string;
}

// 内容接口定义
export interface Content {
  id: string;
  user_id?: string;
  author_id?: string;
  type: 'video' | 'image' | 'article' | 'guide';
  title: string;
  content?: string;
  description?: string;
  media_url?: string;
  category?: string;
  tags: string[];
  view_count?: number;
  like_count?: number;
  comment_count?: number;
  duration?: number; // 视频时长（秒）
  status?: 'draft' | 'published' | 'archived';
  created_at: string;
  updated_at?: string;
}

// 成长记录接口定义
export interface GrowthRecord {
  id: string;
  baby_id: string;
  date: string;
  weight?: number;
  height?: number;
  notes?: string;
  created_at: string;
}

/**
 * 获取当前用户信息
 * @returns Promise<User | null>
 */
export const getCurrentUser = async (): Promise<User | null> => {
  try {
    const { data: { user }, error } = await supabase.auth.getUser();
    
    if (error || !user) {
      return null;
    }
    
    // 获取用户详细信息
    const { data: userProfile, error: profileError } = await supabase
      .from(TABLES.USERS)
      .select('*')
      .eq('id', user.id)
      .single();
    
    if (profileError) {
      console.error('获取用户信息失败:', profileError);
      return null;
    }
    
    return userProfile;
  } catch (error) {
    console.error('获取当前用户失败:', error);
    return null;
  }
};

/**
 * 用户登录
 * @param phone 手机号
 * @param code 验证码
 * @returns Promise<User | null>
 */
export const signInWithPhone = async (phone: string, code: string): Promise<User | null> => {
  try {
    // 使用verifyOtp方法验证验证码
    const { data, error } = await supabase.auth.verifyOtp({
      phone,
      token: code,
      type: 'sms'
    });
    
    if (error) {
      throw error;
    }
    
    return await getCurrentUser();
  } catch (error) {
    console.error('手机号登录失败:', error);
    throw error;
  }
};

/**
 * 发送验证码
 * @param phone 手机号
 * @returns Promise<boolean>
 */
export const sendVerificationCode = async (phone: string): Promise<boolean> => {
  try {
    const { error } = await supabase.auth.signInWithOtp({
      phone
    });
    
    if (error) {
      throw error;
    }
    
    return true;
  } catch (error) {
    console.error('发送验证码失败:', error);
    throw error;
  }
};

/**
 * 用户注销
 * @returns Promise<boolean>
 */
export const signOut = async (): Promise<boolean> => {
  try {
    const { error } = await supabase.auth.signOut();
    
    if (error) {
      throw error;
    }
    
    return true;
  } catch (error) {
    console.error('用户注销失败:', error);
    return false;
  }
};

/**
 * 上传文件到存储桶
 * @param bucket 存储桶名称
 * @param filePath 文件路径
 * @param file 文件数据
 * @returns Promise<string | null> 返回文件URL
 */
export const uploadFile = async (
  bucket: string, 
  filePath: string, 
  file: File | Blob
): Promise<string | null> => {
  try {
    const { data, error } = await supabase.storage
      .from(bucket)
      .upload(filePath, file, {
        cacheControl: '3600',
        upsert: true
      });
    
    if (error) {
      throw error;
    }
    
    // 获取公共URL
    const { data: { publicUrl } } = supabase.storage
      .from(bucket)
      .getPublicUrl(filePath);
    
    return publicUrl;
  } catch (error) {
    console.error('文件上传失败:', error);
    return null;
  }
};

/**
 * 删除存储文件
 * @param bucket 存储桶名称
 * @param filePath 文件路径
 * @returns Promise<boolean>
 */
export const deleteFile = async (bucket: string, filePath: string): Promise<boolean> => {
  try {
    const { error } = await supabase.storage
      .from(bucket)
      .remove([filePath]);
    
    if (error) {
      throw error;
    }
    
    return true;
  } catch (error) {
    console.error('文件删除失败:', error);
    return false;
  }
};

/**
 * 实时订阅数据变化
 * @param table 表名
 * @param callback 回调函数
 * @param filter 过滤条件
 * @returns 订阅对象
 */
export const subscribeToChanges = (
  table: string,
  callback: (payload: any) => void,
  filter?: string
) => {
  let subscription = supabase
    .channel(`${table}_changes`)
    .on('postgres_changes', {
      event: '*',
      schema: 'public',
      table: table,
      filter: filter
    }, callback);
  
  subscription.subscribe();
  
  return subscription;
};

/**
 * 取消订阅
 * @param subscription 订阅对象
 */
export const unsubscribe = (subscription: any) => {
  if (subscription) {
    subscription.unsubscribe();
  }
};

/**
 * 检查用户是否已认证
 * @returns Promise<boolean>
 */
export const isAuthenticated = async (): Promise<boolean> => {
  try {
    const { data: { session }, error } = await supabase.auth.getSession();
    if (error) {
      console.error('获取认证状态失败:', error);
      return false;
    }
    return !!session;
  } catch (error) {
    console.error('检查认证状态异常:', error);
    return false;
  }
};

/**
 * 获取认证状态变化监听器
 * @param callback 状态变化回调
 * @returns 取消监听函数
 */
export const onAuthStateChange = (callback: (event: string, session: any) => void) => {
  const { data: { subscription } } = supabase.auth.onAuthStateChange(callback);
  
  return () => {
    subscription?.unsubscribe();
  };
};

// 导出默认配置
export default {
  supabase,
  TABLES,
  STORAGE_BUCKETS,
  getCurrentUser,
  signInWithPhone,
  sendVerificationCode,
  signOut,
  uploadFile,
  deleteFile,
  subscribeToChanges,
  unsubscribe,
  isAuthenticated,
  onAuthStateChange
};